import { number } from "@intlify/core-base";
import { uuidCreate } from "./uuid";
import i18n from "@/locals";
export function formatNumber(m: number) {
    // 将数字转换为字符串
    let num = m.toString();
    // 分割整数部分和小数部分
    var parts = num.split(".");
    // 整数部分每三位加逗号
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    // 将整数部分和小数部分重新组合
    return parts.join(".");
}

// export function formatBigNumber(value: any, fixNum = 3) {
//     if (!value) {
//         return 0;
//     }
//     var v = +value;
//     if (isNumber(v)) {
//         if (v > 0) {
//             if (v > 1000000000) {
//                 return (v < 0 ? "-" : "") + "".concat(Number(v / 1000000000).toFixed(fixNum), "B");
//             }
//             if (v > 1000000) {
//                 return (v < 0 ? "-" : "") + "".concat(Number(v / 1000000).toFixed(fixNum), "M");
//             }
//             if (v > 1000) {
//                 return (v < 0 ? "-" : "") + "".concat(Number(v / 1000).toFixed(fixNum), "K");
//             }
//             return v;
//         } else {
//             return v;
//         }
//     }
//     return "".concat(value);
// }

export function formatBigNumber(value: any, fixNum = 2): string | number {
    if (!value) return "0";
    if (typeof value !== "number" && typeof value !== "string") {
        return value;
    }

    const num = +value;
    if (isNaN(num)) {
        return value;
    }

    const isNegative = num < 0;
    const absValue = Math.abs(num);

    if (absValue >= 1000000000) {
        return (isNegative ? "-" : "") + (absValue / 1000000000).toFixed(fixNum) + "B";
    } else if (absValue >= 1000000) {
        return (isNegative ? "-" : "") + (absValue / 1000000).toFixed(fixNum) + "M";
    } else if (absValue >= 1000) {
        return (isNegative ? "-" : "") + (absValue / 1000).toFixed(fixNum) + "K";
    } else {
        return isNegative ? "-" + absValue.toFixed(fixNum) : absValue.toFixed(fixNum);
    }
}

export function formatKey(timestamp: any) {
    // return String(timestamp).substring(4) + "_" + String(Math.random()).substring(4);
    return uuidCreate();
}

export function isNumber(value: any) {
    return typeof value === "number" && !isNaN(value);
}

export function formatTimestamp(timestamp: number) {
    // // 纽约时区的偏移量为 UTC-4（考虑夏令时）
    // const newYorkTimeZoneOffset = -4 * 60 * 60 * 1000;

    // // 上海时区的偏移量为 UTC+8
    // const shanghaiTimeZoneOffset = 8 * 60 * 60 * 1000;

    // // 将纽约时间戳转换为上海时间戳
    // const shanghaiTimeStamp = timestamp + (shanghaiTimeZoneOffset - newYorkTimeZoneOffset);

    // const date = new Date(shanghaiTimeStamp);

    const date = new Date(timestamp);

    const year = date.getFullYear();
    const month = ("0" + (date.getMonth() + 1)).slice(-2);
    const day = ("0" + date.getDate()).slice(-2);
    const hours = ("0" + date.getHours()).slice(-2);
    const minutes = ("0" + date.getMinutes()).slice(-2);
    const seconds = ("0" + date.getSeconds()).slice(-2);
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
/*  */
export function partDate(timestamp: number) {
    // const weeks = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
    const weeks = [
        i18n.global.t("message.Weeks.g"),
        i18n.global.t("message.Weeks.a"),
        i18n.global.t("message.Weeks.b"),
        i18n.global.t("message.Weeks.c"),
        i18n.global.t("message.Weeks.d"),
        i18n.global.t("message.Weeks.e"),
        i18n.global.t("message.Weeks.f")
    ];
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = ("0" + (date.getMonth() + 1)).slice(-2);
    const day = ("0" + date.getDate()).slice(-2);
    const dateValue = {
        week: "",
        year: "",
        month: "",
        day: ""
    };
    dateValue.week = weeks[date.getDay()];
    dateValue.year = `${year}`;
    dateValue.month = `${month}`;
    dateValue.day = `${day}`;
    return dateValue;
}
export function getFormatTime(t: number, format: string) {
    if (!t) return "";
    const currentDate = new Date(t);
    const year = currentDate.getFullYear();
    const month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
    const day = ("0" + currentDate.getDate()).slice(-2);
    const hours = ("0" + currentDate.getHours()).slice(-2);
    const minutes = ("0" + currentDate.getMinutes()).slice(-2);
    const seconds = ("0" + currentDate.getSeconds()).slice(-2);
    switch (format) {
        case "yyyy":
            return `${year}`;
        case "yyyy-MM":
            return `${year}-${month}`;
        case "yyyy-MM-dd":
            return `${year}-${month}-${day}`;
        case "yyyy-MM-dd hh":
            return `${year}-${month}-${day} ${hours}`;
        case "yyyy-MM-dd hh:mm":
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        case "yyyy-MM-dd hh:mm:ss":
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        case "MM-dd":
            return `${month}-${day}`;
    }
}
export function formatTimeAgo(timestamp: any) {
    const seconds = Math.floor((Date.now() - timestamp) / 1000);

    if (seconds < 60) {
        // return seconds + "秒前";
        // return seconds + i18n.global.t("message.JNeWs.j");
        return i18n.global.t("message.JNeWs.j");
    }

    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) {
        // return minutes + "分钟前";
        return minutes + i18n.global.t("message.JNeWs.e");
    }

    const hours = Math.floor(minutes / 60);
    if (hours < 24) {
        // return hours + "小时前";
        return hours + i18n.global.t("message.JNeWs.f");
    }

    const days = Math.floor(hours / 24);
    if (days < 30) {
        // return days + "天前";
        return days + i18n.global.t("message.JNeWs.g");
    }

    const months = Math.floor(days / 30);
    if (months < 12) {
        // return months + "个月前";
        return months + i18n.global.t("message.JNeWs.h");
    }

    const years = Math.floor(months / 12);
    // return years + "年前";
    return years + i18n.global.t("message.JNeWs.i");
}

export function isValidEmail(email: string) {
    // 定义邮箱验证的正则表达式
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    // 使用正则表达式的test方法来检查邮箱地址
    return emailRegex.test(email);
}

export function toChartData(data: any) {
    return {
        close: data.close,
        high: data.high,
        low: data.low,
        open: data.open,
        timestamp: data.startTime,
        volume: data.volume,
        fundingRate: data.fundingRate || 0,
        done: data.barType != "S1" && data.x,
        symbol: data.symbol,
    };
}

/**
 * 格式化时间戳为本地时间
 *
 * @param {number} timestamp - 要格式化的时间戳（以毫秒为单位）
 * @returns {string} 格式化后的本地时间，例如 "2023-10-28 15:30:00"
 */
export function formattedDate(timestamp: number) {
    const str = new Intl.DateTimeFormat("en-US", {
        timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit"
    }).format(new Date(timestamp));
    return str;
}

export function numberWithComma(chars: number) {
    const str = String(formatBigNumber(chars));
    const arrChar = Array.from(str.matchAll(/[A-z]/g))[0];
    if (!arrChar) return;
    const start = str.slice(0, arrChar.index);
    const end = str.slice(arrChar.index);
    return numberWithCommas(start) + end;
}


/*
 * @Description: 金额格式化    123456789.123456789 => 123,456,789.123
 */
export function numberWithCommas(num: any, end_: number = 3) {
    if (num == 0) return "0";
    if (!num) return "";
    const str = num.toString();
    const end = str.slice(str.indexOf(".")).slice(0, end_);
    let strs = "";
    if (str.indexOf(".") !== -1) {
        strs = str.slice(0, str.indexOf(".")).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        return strs.concat(end);
    } else {
        strs = str.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        return strs;
    }
}
export function numberWithCommasTwo(num: any, end_: number = 3) {
    if (num == 0) return "0";
    if (!num) return "";
    const str = num.toString();
    const end = str.slice(str.indexOf("."));
    let strs = "";
    if (str.indexOf(".") !== -1) {
        strs = str.slice(0, str.indexOf(".")).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        return strs.concat(end);
    } else {
        strs = str.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + ".00";
        return strs;
    }
}
// 科学计数法转换数字
export function scientificToDecimal(num_str: any) {
    if (!num_str) return "";
    num_str = num_str.toString();
    if (num_str.indexOf("e") == -1) {
        return num_str;
    }
    if (num_str.indexOf("+") != -1) {
        num_str = num_str.replace("+", "");
    }
    if (num_str.indexOf("E") != -1 || num_str.indexOf("e") != -1) {
        let resValue: any = "",
            power: any = '',
            result: any = null,
            dotIndex: any = 0,
            resArr: any = [],
            sym: any = "";
        var numStr = num_str.toString();
        if (numStr[0] == "-") {
            // 如果为负数，转成正数处理，先去掉‘-’号，并保存‘-’.
            numStr = numStr.substr(1);
            sym = "-";
        }
        if (numStr.indexOf("E") != -1 || numStr.indexOf("e") != -1) {
            var regExp = new RegExp(
                "^(((\\d+.?\\d+)|(\\d+))[Ee]{1}((-(\\d+))|(\\d+)))$",
                "ig"
            );
            result = regExp.exec(numStr);
            if (result != null) {
                resValue = result[2];
                power = result[5];
                result = null;
            }
            if (!resValue && !power) {
                return false;
            }
            dotIndex = resValue.indexOf(".") == -1 ? 0 : resValue.indexOf(".");
            resValue = resValue.replace(".", "");
            resArr = resValue.split("");
            if (Number(power) >= 0) {
                var subres = resValue.substr(dotIndex);
                power = Number(power);
                //幂数大于小数点后面的数字位数时，后面加0
                for (var i = 0; i <= power - subres.length; i++) {
                    resArr.push("0");
                }
                if (power - subres.length < 0) {
                    resArr.splice(dotIndex + power, 0, ".");
                }
            } else {
                power = power.replace("-", "");
                power = Number(power);
                //幂数大于等于 小数点的index位置, 前面加0
                for (var i = 0; i < power - dotIndex; i++) {
                    resArr.unshift("0");
                }
                var n = power - dotIndex >= 0 ? 1 : -(power - dotIndex);
                resArr.splice(n, 0, ".");
            }
        }
        resValue = resArr.join("");
        // console.log(`
        // 	处理科学计数法前:${num_str}
        // 	转换后:${sym + resValue}
        // `)
        return sym + resValue;
    } else {
        return num_str;
    }


    // return number
}

export function fixNumber(num: number, fix = 2) {
    let zeros = new Array(fix).fill("0").join("");
    let val: any = Math.abs(num);
    val = numberWithCommas(val, fix + 1);
    if (val.indexOf(".") == -1) {
        return val + "." + zeros;
    }
    let ary = val.split(".");
    let prev = num >= 0 ? "" : "-";
    return prev + ary[0] + "." + (ary[1] + zeros).substring(0, fix);
}

export function formatHashName(str: string | undefined) {
    if (!str) return "";
    const prefix = '0x';
    const head = str.slice(2, 7);
    const tail = str.slice(-5);
    return `${prefix}${head}...${tail}`
}
// function tests() {
// 	for (var i = 0; i < 30; i++) {
// 		var num = 1000000 * (Math.random() - 0.5);
// 		var aim = fixNumber(num, 4);
// 		console.log("------", num, aim)
// 	}

// }
// tests();